﻿using System;

namespace Birkelund.QueryStrings.Tokens
{
    /// <summary>
    /// Class to provide querystring tokens of datatype <see cref="Uri"/>
    /// </summary>
    public class UriToken : QueryStringTokenBase<Uri>, IRenderIfNullOrEmptyValue
    {
        /// <summary>
        /// Gets or sets a value indicating whether a value shoud be rendered if it is null or empty.
        /// </summary>
        /// <value><c>true</c> or <c>false</c>.</value>
        public virtual bool RenderIfEmptyValue { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="UriToken"/> class.
        /// </summary>
        /// <param name="keyName">The key.</param>
        public UriToken(string keyName)
            : base(keyName)
        {
        }

        /// <summary>
        /// Parses from string value.
        /// </summary>
        /// <param name="stringValue">The string value.</param>
        /// <returns></returns>
        protected override Uri OnParseFromString(string stringValue)
        {
            if (string.IsNullOrEmpty(stringValue))
            {
                return null;
            }
            return new Uri(stringValue);
        }

        /// <summary>
        /// Render the token value
        /// </summary>
        /// <param name="value">The value</param>
        /// <returns></returns>
        protected override string OnRenderTokenValue(Uri value)
        {
            if (value == null)
                return null;

            return value.ToString();
        }
    }
}